package com.chidopi.market.bookstore.actions;

import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.beanutils.DynaBean;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chidopi.cdf.service.IBaseService;
import com.chidopi.cdf.struts1actions.CdfDispatchAction;
import com.chidopi.cdf.util.ModelContextFactory;
import com.chidopi.market.bookstore.domain.BookCities;
import com.chidopi.market.bookstore.service.IDownloadStatService;
import com.chidopi.market.bookstore.service.IResourceService;

public class DownloadStatAction extends CdfDispatchAction {
	private static Logger logger = LoggerFactory.getLogger(DownloadStatAction.class);
	private IDownloadStatService dsService;
	private IBaseService<BookCities> bookCitiesService;
	private IResourceService resService;
	
	public DownloadStatAction() {
		try {
			this.bookCitiesService = (IBaseService<BookCities>)
				ModelContextFactory.get("bookCitiesService", IBaseService.class);
		} catch (Exception e) {
			this.dsService = null;
			logger.warn("initial bookCitiesService", e);
		}
		
		try {
			this.dsService = 
				ModelContextFactory.getT("downloadStatService", IDownloadStatService.class);
		} catch (Exception e) {
			this.dsService = null;
			logger.warn("initial IDownloadStatService", e);
		}
		
		try {
			this.resService = 
				ModelContextFactory.getT("resourceService", IResourceService.class);
		} catch (Exception e) {
			this.dsService = null;
			logger.warn("initial bookCitiesService", e);
		}
	}
	
	public ActionForward init(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		DynaBean dynaForm = (DynaBean) form;
		List<BookCities> list = this.bookCitiesService.find(null);		
		dynaForm.set("bookcities", list);
		//logger.info("bookcities:" + list);
		return mapping.findForward("success");
	}
	
	public ActionForward query(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String info_type = request.getParameter("info_type");
		List<Map<String, Object>> result ;
		if ("stat".equals(info_type)) {
			result = this.dsService.queryDownloadStat(request);
		} else {
			result = this.dsService.queryDownloadDetail(request);
		}
		PrintWriter out=response.getWriter();
		if (result == null || result.size() == 0) {
	        out.println("[]");
	        out.flush();
			return null;			
		}

		JSONArray json = JSONArray.fromObject(result);
		logger.debug(json.toString());
        out.println(json);
        out.flush();
		return null;
	}
	
	public ActionForward genCSV(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String info_type = request.getParameter("info_type");
		List<Map<String, Object>> result ;
		if ("stat".equals(info_type)) {
			result = this.dsService.queryDownloadStat(request);
		} else {
			result = this.dsService.queryDownloadDetail(request);
		}
		StringBuffer sb = new StringBuffer();
		for (Map<String, Object> map : result) {
			for (Object obj : map.values()) {
				sb.append(obj);
				sb.append(",");
			}
			sb.append("\n");
		}
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition",
			"attachment;filename=data.csv");
		ServletOutputStream out = response.getOutputStream();
		out.write(sb.toString().getBytes("UTF-8"));
		out.flush();
		out.close();
		return null;
	}
	
	/*
	public ActionForward genCSV(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String csv = request.getParameter("csv");
		logger.debug(csv);
		csv = csv.replaceAll("!;", "\n");
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition",
			"attachment;filename=data.csv");
		ServletOutputStream out = response.getOutputStream();
		out.write(csv.getBytes("UTF-8"));
		out.flush();
		out.close();
		logger.debug("flush!!");
		return null;
	} */
}
